package xyz.hubery.aspect;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xyz.hubery.model.R;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理内部API调用异常
     */
    @ExceptionHandler(value = ApiException.class)
    public R handleApiException(ApiException e) {
        if(e.getErrorCode() != null) {
            return R.fail(e.getErrorCode(),e.getMessage());
        }
        return R.fail(e.getMessage());
    }

    /**
     * 处理参数校验失败异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if(bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if(fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }

        return R.fail(message);
    }

    /**
     * 处理对象Validation异常
     */
    @ExceptionHandler(value = BindException.class)
    public R handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if(bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if(fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }

        return R.fail(message);
    }


}
